#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n, m, a[25][25];
set<ll> mx[25];
ll ans, d[60];

void dfs1(ll x, ll y, ll val) {
  if (x + y == n + 1) {
    // cout<<x<<' '<<y<<' '<<val<<endl;
    mx[x].insert((val * d[n - 1]) % m);
    return;
  }
  dfs1(x + 1, y, (val * 10 + a[x + 1][y]) % m);
  dfs1(x, y + 1, (val * 10 + a[x][y + 1]) % m);
}

void dfs2(ll x, ll y, ll val) {
  if (x + y == n + 1) {
    // cout<<x<<' '<<y<<' '<<val<<endl;
    if ((*mx[x].begin()) < m - val) {
      auto res = mx[x].lower_bound(m - val);
      res--;
      ans = max(*res + val, ans);
    } else {
      auto res = mx[x].rbegin();
      ans = max((*res + val) % m, ans);
    }
    return;
  }
  dfs2(x - 1, y, (val + a[x][y] * d[2 * n - x - y]) % m);
  dfs2(x, y - 1, (val + a[x][y] * d[2 * n - x - y]) % m);
}


int main() {
  cin >> n >> m;
  d[0] = 1;
  for (int i = 1; i <= 2 * n; i++)
    d[i] = d[i - 1] * 10 % m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++)
      cin >> a[i][j];
  dfs1(1, 1, a[1][1]);
  dfs2(n, n, 0);
  cout << ans << endl;
  return 0;
}
